import { login } from 'api/user.js';
const TOKEN_KEY = 'token';
const USER_INFO_KEY = 'user-info'

export default {
    namespaced: true,
    state: () => ({
        token: uni.getStorageSync(TOKEN_KEY) || '',
        userInfo: uni.getStorageSync(USER_INFO_KEY) || {},
    }),
    mutations: {
        // 保存token到vuex
        setToken(state, token) {
            state.token = token;
            this.commit('user/saveToToken')
        },
        // 保存userInfo到vuex
        setUserInfo(state, userInfo) {
            state.userInfo = userInfo;
            this.commit('user/saveToUserInfo')
        },
        // 保存token到本地存储
        saveToToken(state) {
            uni.setStorage({
                key: TOKEN_KEY,
                data: state.token,
            })
        },
        // 保存userInfo到本地存储
        saveToUserInfo(state) {
            uni.setStorage({
                key: 'USER_INFO_KEY',
                data: state.userInfo,
            })
        },
        // 删除token
        removeToken(state) {
            state.token = '';
            this.commit('user/saveToToken')
        },
        // 删除token
        removeUserInfo(state) {
            state.userInfo = '';
            this.commit('user/saveToUserInfo')
        }
    },
    actions: {
        // 完成登录
        async login(context, userProfile) {
            const userInfo = userProfile.userInfo;
            // 调用登录接口
            const { data: res } = await login({
                signature: userProfile.signature,
                iv: userProfile.iv,
                nickName: userInfo.nickName,
                gender: userInfo.gender,
                city: userInfo.city,
                province: userInfo.province,
                avatarUrl: userInfo.avatarUrl
            })
            this.commit('user/setToken', res.token)
            this.commit('user/setUserInfo', userInfo)
        },
        // 退出登录
        loginOut() {
            this.commit('user/removeToken');
            this.commit('user/removeUserInfo');
        },
        async isLogin(context) {
            if (context.state.token) return true;
            // 如果用户未登录，则引导用户登录
            const [error, res] = await uni.showModal({
                title: '登录之后才可以进行后续操作',
                content: '立即跳转到登录页面?(登录后会自动返回当前页面哦~~)'
            })
            const { cancel, confirm } = res;
            if (confirm) {
                uni.navigateTo({ url: '/subpkg/pages/login-page/login-page' })
            }
            return false
        }
    },
}